from channels.generic.websocket import WebsocketConsumer
from channels.exceptions import StopConsumer
from asgiref.sync import async_to_sync
import json
from distutils.util import strtobool
import sys;

sys.path.append("./app")
from views import *


class WS(WebsocketConsumer):
    #   接受客户端连接
    def websocket_connect(self, message):
        self.accept()
        print('连接')

    def websocket_receive(self, message):
        content = json.loads(message['text'])
        if content['type'] == 1:  # 获取运动数据
            #   direction和carIP
            direction = content['direction']
            carIP = content['carIP']
            direction = direction.split(',')
            for _ in range(4):
                direction[_] = strtobool(direction[_])
            handle_car_move(direction, carIP)

    def websocket_disconnect(self, message):
        raise StopConsumer()